import router from './router'
import store from '@/store'
// 引入进度条
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/get-page-title'

import Watermark from '@/utils/watermark'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  document.title = getPageTitle(to.meta.title)
  if (store.getters.token) {
    // 如果有token
    if (to.path === '/login') {
      // 如果访问登陆页面直接跳转主页
      next('/')
    } else {
      if (!store.getters.studentname) {
        const { roles } = await store.dispatch('user/getUserInfo')
        // console.log(roles.menu)
        const routes = await store.dispatch('permission/filterRoutes', roles.menu)
        // console.log(routes)
        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        // 访问其他页面直接跳转
        next()
      }
    }
  } else {
    // 无token
    if (whiteList.indexOf(to.path) > -1) {
      // 要去的地址在白名单
      next()
    } else {
      next('/login')
    }
  }
  nprogress.done()
})

router.afterEach(() => {
  // finish progress bar
  nprogress.done()
  if (store.getters.studentname) {
    Watermark.set([store.getters.studentid, store.getters.studentname], {
      top: 0
    })
  }
})
